<template>
  <a-spin :spinning="headLoading">
    <a-row justify="space-between" style="margin-bottom: 16px">
      <a-col style="padding: 5px" v-bind="{xl: 20 }">
        <a-row>
          <a-col>
            <span class="titleTxt">订单编号：</span>
            <span class="titleTxt">{{orderId}}</span>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
  </a-spin>
  <a-divider style="height: 1px; background-color: #797979"/>
  <a-descriptions :column="{ xs: 1, sm: 3, md: 4, lg: 4, xl: 5 }" style="margin-top:10px">
    <a-descriptions-item label="平台">{{headContent.platform}}</a-descriptions-item>
    <a-descriptions-item label="状态">{{headContent.orderStatus}}</a-descriptions-item>
    <a-descriptions-item label="币种">{{headContent.currency}}</a-descriptions-item>
    <a-descriptions-item label="订单金额">
      <span style="font-size: 18px; font-weight: 600;position: relative;top:60%;left:-20%">{{headContent.invoicedAmount}}</span>
    </a-descriptions-item>
    <a-descriptions-item label="退款金额">
      <span style="font-size: 18px; font-weight: 600;position: relative;top:60%;left:-20%">{{toDecimal(headContent.totalTaxRefund)}}</span>
    </a-descriptions-item>
    <a-descriptions-item label="下单时间">{{headContent.orderCreatedTime}}</a-descriptions-item>
    <a-descriptions-item label="下单邮箱">{{headContent.billingEmail}}</a-descriptions-item>
    <a-descriptions-item label="订单类型">{{headContent.orderType}}</a-descriptions-item>
  </a-descriptions>
  <a-divider style="height: 1px; background-color: #797979"/>
  <a-descriptions title="当前订单商品信息" style="margin-top:10px">
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>收件人</span>
      </template>
      <a-input v-model:value="shipping.shippingCustName" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label">邮箱</span>
      </template>
      <a-input v-model:value="shipping.shippingEmail" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label">收货人电话</span>
      </template>
      <a-input v-model:value="shipping.shippingTelephone" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label">收货人地区（省/州）</span>
      </template>
      <a-input v-model:value="shipping.shippingRegion" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>收货人地址（城市）</span>
      </template>
      <a-input v-model:value="shipping.shippingCity" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>邮编</span>
      </template>
      <a-input v-model:value="shipping.shippingPostcode" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>收件人地址1</span>
      </template>
      <a-input v-model:value="shipping.shippingStreetLine1" style="width:200px"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>重发原因</span>
      </template>
      <a-cascader v-model:value="value" :options="options"
                  :allowClear="false"
                  @change="handleReasonChange"
                  :field-names="{ label: 'reason', value: 'reason', children: 'childrenReasonList' }">
      </a-cascader>
    </a-descriptions-item>
    <a-descriptions-item v-if="showDelivery">
      <template #label>
        <span class="label"><span style="color:red">*</span>该重发单原单是否妥投过</span>
      </template>
      <a-select v-model:value="sourceDeliveryFlag" style="width: 100px">
        <a-select-option value="Y">是</a-select-option>
        <a-select-option value="N">否</a-select-option>
      </a-select>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label">客服备注</span>
      </template>
      <a-textarea  v-model:value="remark" style="width: 200px" placeholder="请输入备注"/>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label">期望指定发货仓</span>
      </template>
      <a-select :filter-option="filterOption" showSearch allow-clear  v-model:value="warehouseName" style="width: 200px" placeholder="请选择发货仓">
        <a-select-option  v-for="option in operationOptions" :label="option.label"  :key="option.value" :value="option.value">{{ option.label }}</a-select-option>
      </a-select>
    </a-descriptions-item>
    <a-descriptions-item>
      <template #label>
        <span class="label"><span style="color:red">*</span>图片</span>
      </template>
      <uploadImage :action="apiBaseUrl + `sys/common/upload?biz=wms/resend`" v-model:list="photoList" />
    </a-descriptions-item>
  </a-descriptions>
  <a-divider style="height: 1px; background-color: #797979"/>
  <a-button type="primary" style="margin-top: 10px" @click="addWarehouseSku">添加仓库SKU</a-button>
<!--  <a-button type="primary" v-show="type === '2' " style="margin-top: 10px" @click="addProductSku">添加整包平台SKU</a-button>-->
  <common-table
      v-if="type === '1' "
      :columns="partsColumns"
      :dataSource="partsDataList"
      :rowKey="(record) => record"
      :scroll="{ x: 'max-content'}"
      :row-selection="{onChange: rowSelectionChange1,selectedRowKeys: selectedRowKeys1}"
      :slots="['retransmissionAmount','operation','headerCell','confirmVersionFlag']"
  >
    <template #headerCell="{column,record}">
      <span v-if="column.title === '重发单商品选择操作'">
        <span style="color:red">*</span>重发单商品选择操作
      </span>
      <span v-if="column.title === '重发单商品数量'">
        <span style="color:red">*</span>重发单商品数量
      </span>
    </template>
    <template #operation="{ record }">
      <a-select ref="selectRef" :filter-option="filterOption" @contextmenu="handleContextMenu" showSearch allow-clear  @change="changeOptions(record)" :disabled="!selectedRowKeys1.includes(record)" v-model:value="record.operation" style="width: 200px" placeholder="请选择仓库SKU">
        <a-select-option :disabled="selected.includes(option)" v-for="option in skuOptions" :label="option"  :key="option" :value="option">{{ option }}</a-select-option>
      </a-select>
    </template>
    <template #confirmVersionFlag="{ record }">
      <a-switch v-model:checked="record.confirmVersionFlag" checked-children="是" un-checked-children="否" />
    </template>
    <template #retransmissionAmount="{ record }">
      <a-input-number :precision="0" :min="1" :step="1" :disabled="!selectedRowKeys1.includes(record)" v-model:value="record.retransmissionAmount"  style="width: 100px"/>
    </template>
  </common-table>
  <div class="bottom">
    <a-button type="primary" @click="$router.go(-1)">取消</a-button>
    <a-popconfirm
        title="是否提交重发单?"
        ok-text="是"
        cancel-text="否"
        @confirm="handleSubmit"
    >
      <a-button type="primary" style="margin-left: 100px">确定提交重发单</a-button>
    </a-popconfirm>
  </div>
</template>
<script setup>
import CommonTable from "@/components/commonTable/index.vue";
import {
  createResend,
  getOrderDetail,
  getOrderItem, getProductSkuVersion,
  getReasonTree, getResendWarehouseSkuInfo,
  getShipping,
  getWarehouseOfSelectResend, getWarehouseSkuOfSelectResend,
} from "@/api/standard/index.js";
import {message} from "ant-design-vue";
import {toDecimal} from "@utils/utils.js";
import uploadImage from "@/components/upload/uploadImg.vue";
import {apiBaseUrl} from "@utils/service/index.js";
import {useRouter,useRoute} from "vue-router";
const headLoading = ref(false)
const route = useRoute()
const router = useRouter()
const selectRef = ref(null)
const orderId = ref(route.query.orderId)
const type = ref("1")
const value = ref([])
const photoList = ref([])
const remark = ref('')
const warehouseName = ref('')
const headContent = ref({})
const shipping = ref({})
const partsDataList = ref([])
const selectedRowKeys1 = ref([])
const operationOptions = ref([])
const skuOptions = ref([])
const sourceDeliveryFlag = ref('')
const showDelivery = ref(false)
const filterOption = (input, option) => {
  return option.label.toUpperCase().indexOf(input.toUpperCase()) >= 0;
};
const handleReasonChange = () => {
  sourceDeliveryFlag.value = ''
  showDelivery.value = value.value[0] === '客户原因';
}
const partsColumns = [
  {
    title:'原订单仓库SKU',
    dataIndex:'warehouseSku',
    align:'center',
  },
  {
    title:'原订单数量',
    dataIndex:'qty',
    align:'center',
  },
  {
    title:'重发单商品选择操作',
    dataIndex:'operation',
    align:'center',
  },
  {
    title:'重发商品中文名称',
    dataIndex:'resendWarehouseSkuName',
    align:'center',
  },
  {
    title:'是否指定选择的重发单商品版本发货',
    dataIndex:'confirmVersionFlag',
    align: 'center'
  },
  {
    title:'当前选择重发的仓库SKU可兼容版本',
    dataIndex:'compatibleVersion',
    align:'center',
  },
  {
    title:'重发单商品数量',
    dataIndex:'retransmissionAmount',
    align:'center',
  },
]

const rowSelectionChange1 = (e) => {
  selectedRowKeys1.value = e
}

const addWarehouseSku = () => {
  partsDataList.value.push({
    retransmissionAmount:1,
    confirmVersionFlag:false
  })
}

const options = ref([])
const selected = ref([])
const changeOptions = async (record) => {
  selected.value = []
  partsDataList.value.forEach(item => {
    if(item.operation !== null && item.operation !== undefined && item.operation !== ''){
      selected.value.push(item.operation)
    }
  })
  const res = await getResendWarehouseSkuInfo({warehouseSku:record.operation})
  record.resendWarehouseSkuName = res.result.resendWarehouseSkuName
  record.compatibleVersion = res.result.compatibleVersion
  record.productSku = res.result.productSku
  record.versionCode = res.result.versionCode
}


const handleSubmit = async () => {
  try {
    console.log(selectedRowKeys1.value)
    if(shipping.value.shippingCustName === '' ){
      return message.error('请填写收件人信息')
    }
    if(shipping.value.shippingCity === ''){
      return message.error('请填写收件人地址')
    }
    if(shipping.value.shippingPostcode === ''){
      return message.error('请填写邮编')
    }
    if(shipping.value.shippingStreetLine1 === ''){
      return message.error('请填写收件人地址1')
    }
    if(value.value.length === 0){
      return message.error('请选择重发原因')
    }
    if(value.value[0] === '客户原因' && sourceDeliveryFlag.value === ''){
      return message.error('请选择该重发单原单是否妥投过')
    }
    if(photoList.value.length === 0){
      return message.error('请上传图片')
    }
    if(selectedRowKeys1.value.length === 0){
      return message.error('请选择重发商品')
    }
    for (let i = 0; i < selectedRowKeys1.value.length; i++) {
      if(selectedRowKeys1.value[i].operation === null || selectedRowKeys1.value[i].operation === undefined || selectedRowKeys1.value[i].operation === ''){
        return message.error('请选择重发仓库SKU')
      }
      if(selectedRowKeys1.value[i].retransmissionAmount === null || selectedRowKeys1.value[i].retransmissionAmount === undefined || selectedRowKeys1.value[i].retransmissionAmount === ''){
        return message.error('请选择重发数量')
      }
    }
    let obj = {
      saleOrderCode:route.query.saleOrderCode,
      warehouse:warehouseName.value === undefined ? '' : warehouseName.value,
      orderId:orderId.value,
      cscRemark:remark.value,
      firstReason:value.value[0],
      secondReason:value.value[1],
      thirdReason:value.value[2],
      sourceDeliveryFlag:sourceDeliveryFlag.value,
      orderAddress:{
        shippingCustName:shipping.value.shippingCustName,
        shippingEmail:shipping.value.shippingEmail,
        shippingTelephone:shipping.value.shippingTelephone,
        shippingRegion:shipping.value.shippingRegion,
        shippingCity:shipping.value.shippingCity,
        shippingPostcode:shipping.value.shippingPostcode,
        shippingStreetLine1:shipping.value.shippingStreetLine1,
      },
      warehouseSkuList:selectedRowKeys1.value.map(item => {
        return {
          sourceWarehouseSku:item.warehouseSku,
          resendWarehouseSku:item.operation,
          resendQty:item.retransmissionAmount,
          resendWarehouseSkuName:item.resendWarehouseSkuName,
          confirmVersionFlag:item.confirmVersionFlag,
          productSku:item.productSku,
          versionCode:item.versionCode,
        }
      })
    }
    if(photoList.value.length !== 0){
      obj.imgList = photoList.value.map(item => {
        return item.response.message
      }).join(',')
    }
    const res = await createResend(obj)
    if(import.meta.env.NODE_ENV != 'production') {
      message.success(res.message + '重发单创建成功')
    }else {
      message.success(`重发单创建成功, `)
    }
    router.go(-1)
  }catch (e){
    console.log(e)
    message.error(e || '数据获取失败')
  }finally {

  }
}
const init = async () => {
  try{
    const res = await getReasonTree()
    options.value = res.result
  }catch (e){
    message.error(e)
  }
}
const initData = () => {
  getOrderDetail({orderId: orderId.value}).then(res => {
    headContent.value = res.result
  })
  getShipping({orderId: orderId.value}).then(res => {
    shipping.value = res.result
  })
  getOrderItem({saleOrderCode:route.query.saleOrderCode}).then(res => {
    partsDataList.value = res.result.map(item => {
      return {
        ...item,
        retransmissionAmount:1,
        confirmVersionFlag:false
      }
    })
  })
  getWarehouseOfSelectResend().then(res => {
    operationOptions.value = res.result.map(item => {
      return {
        value: item.warehouseCode,
        label: item.warehouseName,
      }
    })
  })
  getWarehouseSkuOfSelectResend().then(res => {
    skuOptions.value = res.result
  })
}
const getProductSkuVersionData = async (productSku,record) => {
  const res = await getProductSkuVersion({productSku})
  record.options = res.result
}

const handleContextMenu = (e) => {
  e.preventDefault()
  const selectedText = e.target.innerText
  if(selectedText) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(selectedText).catch(() => {
        // 备用方案或错误提示
      });
    } else {
      // 使用旧版 execCommand 回退方案
      fallbackCopy(selectedText);
    }
  }
}

// 旧版复制方案
const fallbackCopy = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  try {
    document.execCommand('copy');
    message.success(`${text}, 复制成功`)
  } catch (err) {
    console.error('Fallback copy failed', err);
  }
  document.body.removeChild(textArea);
};

onMounted(() => {
  init()
  initData()
})
</script>
<script>
export default {
  name:'orderStandardization-retransmission'
}
</script>
<style scoped>
.titleTxt{
  line-height: 33px;
  height: 33px;
  font-size: 18px;
  font-weight: 600;
}
.bottom{
  display: flex;
  justify-content: center;
  align-items: center;
  width:100%;
  margin-top: 40px;
}
.label{
  line-height: 32px;
}
</style>
